//
//  ChartView.m
//  柱状图Demo
//
//  Created by mac on 16/6/5.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ChartView.h"

#define yieldLineSpace 4
#define lineLeftMargin 60
#define lineRightMargin 10
#define lineTopMargin 10
#define lineBottomMargin 30
#define lineWidth 0.5f
#define itemLeftMargin 16
#define itemRightMargin 16
#define itemSpace 6
#define itemWidthRatio (5/12.f)
#define WIDTH   self.frame.size.width  // 宽
#define HEIGHT  self.frame.size.height // 高
#define positiveItemHexColor 0xe83846   //正收益条颜色值
#define negativeItemHexColor 0x17c7ba   //负收益条颜色值

#define COLOR_RGB(rgbValue) [UIColor colorWith\
Red     :(rgbValue & 0xFF0000)     / (float)0xFF0000 \
green   :(rgbValue & 0xFF00)       / (float)0xFF00 \
blue    :(rgbValue & 0xFF)         / (float)0xFF \
alpha   :1.0]

@implementation ChartView

- (void)refreshChartWithYields:(NSArray *)yields dayPoints:(NSArray *)dayPoints{
    
    self.yields = yields;
    self.dayPoints = dayPoints;
    [self setNeedsDisplay];
    
}
- (void)drawRect:(CGRect)rect{
    //声明最大收益量
    float maxYield = 0;
    
    // 获取最大收益的绝对值
    
    for (NSNumber *number in _yields) {
        if (maxYield < fabs([number floatValue])) {
            maxYield = fabs([number floatValue]);
        }
    }
    
    // 分几段
    NSInteger sectionNum = 2;
    
    //平均每段的收益
    
    CGFloat sectionYield = maxYield / 2;
    
    UIColor *currentColor = [UIColor blackColor];
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    CGContextBeginPath(contextRef);
    
    CGContextSetLineWidth(contextRef, lineWidth); //设置线粗
    
    CGContextSetStrokeColorWithColor(contextRef, currentColor.CGColor);   //设置画笔颜色
    
    
    
    //中线的y坐标
    
    CGFloat centerLineY = CGRectGetMidY(self.bounds);
    
    //设置段落风格
    
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    
    paragraph.alignment = NSTextAlignmentRight;
    
    //设置字体颜色
    
    UIColor *textColor = [UIColor lightGrayColor];
    
    //设置字体大小
    
    UIFont *textFont = [UIFont systemFontOfSize:10];
    
    
    //0收益中线
    
    CGContextMoveToPoint(contextRef, lineLeftMargin, centerLineY);
    
    CGContextAddLineToPoint(contextRef, CGRectGetMaxX(self.bounds) - lineRightMargin, centerLineY);
    
    CGContextStrokePath(contextRef);
    
    //0收益率
    
    [@"0" drawInRect:CGRectMake(0, centerLineY - 7, lineLeftMargin - yieldLineSpace, lineLeftMargin) withAttributes:@{NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:textColor,NSFontAttributeName:textFont}];
    
    
    
    //线与线的垂直距离
    
    CGFloat lineSpace = (CGRectGetMaxY(self.bounds) - lineTopMargin - lineBottomMargin) / 4.f;
    
    
    
    for (int i = 0; i < sectionNum; i++) {
        
        CGFloat topLineY = centerLineY - lineSpace * (i + 1);
        
        CGFloat bottomLineY = centerLineY + lineSpace * (i + 1);
        
        
        
        //虚线 线宽与空格宽
        
        CGFloat dashes[] = {2,1};
        
        CGContextSetLineDash(contextRef, 0.0, dashes, 2);
        
        
        
        CGContextSetStrokeColorWithColor(contextRef, currentColor.CGColor);   //设置画笔颜色
        
        
        
        //中线以上
        
        CGContextMoveToPoint(contextRef, lineLeftMargin, topLineY);
        
        CGContextAddLineToPoint(contextRef, CGRectGetMaxX(self.bounds) - lineRightMargin, topLineY);
        
        CGContextStrokePath(contextRef);
        //收益率
        
        [[NSString stringWithFormat:@"%.f",sectionYield * (i + 1)] drawInRect:CGRectMake(0, topLineY - 7, lineLeftMargin - yieldLineSpace, lineLeftMargin) withAttributes:@{NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:textColor,NSFontAttributeName:textFont}];
        
        
        
        CGContextSetStrokeColorWithColor(contextRef, currentColor.CGColor);   //设置画笔颜色
        
        
        
        //中线以下
        
        CGContextMoveToPoint(contextRef, lineLeftMargin, bottomLineY);
        
        CGContextAddLineToPoint(contextRef, CGRectGetMaxX(self.bounds) - lineRightMargin, bottomLineY);
        
        CGContextStrokePath(contextRef);
        
        
        
        //负收益率
        
        [[NSString stringWithFormat:@"-%.f",sectionYield * (i + 1)] drawInRect:CGRectMake(0, bottomLineY - 7, lineLeftMargin - yieldLineSpace, lineLeftMargin) withAttributes:@{NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:textColor,NSFontAttributeName:textFont}];
        
    }
    if (0 == _yields.count) {
        
        paragraph.alignment = NSTextAlignmentCenter;
        
        
        
        NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:textColor,NSFontAttributeName:[UIFont systemFontOfSize:40]};
        
        
        
        CGSize textSize = [@"暂无数据" sizeWithAttributes:attributes];
        
        [@"暂无数据" drawInRect:CGRectMake(lineLeftMargin + itemLeftMargin,centerLineY - textSize.height / 2.f, CGRectGetMaxX(self.bounds) - lineLeftMargin - itemLeftMargin - lineRightMargin - itemRightMargin,textSize.height) withAttributes:attributes];
        
        
        return;
        
    }
    NSString *lastDay = [_dayPoints lastObject];
    
    NSInteger partNum = _dayPoints.count;
    
    paragraph.alignment = NSTextAlignmentLeft;
    
    
    //绘制柱状图
    
    CGFloat averageSpace = (CGRectGetMaxX(self.bounds) - lineLeftMargin - itemLeftMargin - lineRightMargin - itemRightMargin) / (partNum - 1);
    
    
    
    //柱宽
    
    CGFloat itemWidth = averageSpace * itemWidthRatio;
    
    
    for (int i=0; i<partNum; i++) {
        
        if (i > _yields.count - 1)  //后面暂时还没收益就不画柱状条
            
        {
            
            break;
            
        }
        NSString *dayStr = nil;
        if (i % 6 == 0) {
            //绘制日期
            dayStr = [NSString stringWithFormat:@"%@",_dayPoints[i]];
            [dayStr drawInRect:CGRectMake(lineLeftMargin + itemLeftMargin - 5 + averageSpace * i, CGRectGetMaxY(self.bounds) - (lineBottomMargin - 15), 50, 15)withAttributes:@{NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:textColor,NSFontAttributeName:textFont}];
        }  else if (i == _yields.count - 1){
            [[NSString stringWithFormat:@"%@",lastDay]  drawInRect:CGRectMake(lineLeftMargin + itemLeftMargin - 5 + averageSpace * i, CGRectGetMaxY(self.bounds) - (lineBottomMargin - 15), 50, 15)withAttributes:@{NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:textColor,NSFontAttributeName:textFont}];
            
        }
        //绘制柱状图
        
        float yield = [_yields[i] floatValue];
        
        
//        float radius = itemWidth/2.f;   //柱状末尾的半圆半径
        
        
        
        //虚线 线宽与空格宽 （之前设了虚线，现在把虚线的间隙变为0）
        
        CGFloat dashes[] = {1,0};
        
        CGContextSetLineDash(contextRef, 0.0, dashes, 2);
        
        CGFloat itemX = lineLeftMargin + itemLeftMargin + averageSpace * i - itemWidth/2.f;
        
        CGFloat itemY = centerLineY - (lineSpace * sectionNum) * yield / maxYield;
        
        //是否要画半圆（如果收益高度低于宽度，就不画半圆）
//        
//        BOOL shouldDrawCircle = (fabs(itemY - centerLineY) > itemWidth/2.f) ? YES : NO;
        
        
        
        if (yield >= 0) {
            
            
//            
//            if (shouldDrawCircle) {
//                
//                itemY += radius;
//                
//            }
            
            
            
            //正收益颜色
            
            CGContextSetStrokeColorWithColor(contextRef, COLOR_RGB(positiveItemHexColor).CGColor);
            
            CGContextSetFillColorWithColor(contextRef, COLOR_RGB(positiveItemHexColor).CGColor);
            
        }
        
        else
            
        {
            
            
//            
//            if (shouldDrawCircle) {
//                
//                itemY -= radius;
//                
//            }
            
            
            //负收益颜色
            
            CGContextSetStrokeColorWithColor(contextRef, COLOR_RGB(negativeItemHexColor).CGColor);
            
            CGContextSetFillColorWithColor(contextRef, COLOR_RGB(negativeItemHexColor).CGColor);
            
        }
        
        
        //        CGContextSetShadow(contextRef,CGSizeMake(2, 0) , 2);  //阴影效果
        
        CGMutablePathRef pathRef = CGPathCreateMutable();
        
        CGPathMoveToPoint(pathRef, NULL, itemX, centerLineY);
        
        CGPathAddLineToPoint(pathRef, NULL, itemX, itemY);
        
        CGPathAddLineToPoint(pathRef, NULL, itemX + itemWidth, itemY);
        
        CGPathAddLineToPoint(pathRef, NULL, itemX + itemWidth, centerLineY);
        
        CGPathCloseSubpath(pathRef);
        
        CGContextAddPath(contextRef, pathRef);
        
        CGContextFillPath(contextRef);
        
        CGContextAddPath(contextRef, pathRef);
        
        CGContextStrokePath(contextRef);
        
    
//        if (shouldDrawCircle) {
//            
//            //画线末圆角
//            
//            CGPathMoveToPoint(pathRef, NULL, itemX + itemWidth/2.f, itemY);
//            
//            if (yield >= 0) {
//                
//                CGPathAddArc(pathRef, NULL, itemX + itemWidth/2.f, itemY, itemWidth/2.f, M_PI, 0, NO);
//                
//            }
//            
//            else
//                
//            {
//                
//                CGPathAddArc(pathRef, NULL, itemX + itemWidth/2.f, itemY, itemWidth/2.f, 0, M_PI, NO);
//                
//            }
//            
//            CGPathCloseSubpath(pathRef);
//            
//            CGContextAddPath(contextRef, pathRef);
//            
//            CGContextFillPath(contextRef);
//            
//            CGContextAddPath(contextRef, pathRef);
//            
//            CGContextStrokePath(contextRef);
//            
//        }
        
    }
}

#pragma mark 懒加载

-(NSArray *)dayPoints{
    
    if (!_dayPoints) {
        _dayPoints = [NSArray array];
    }
    return _dayPoints;
}

-(NSArray *)yields{
    if (!_yields) {
        _yields =[NSArray array];
    }
    return _yields;
}
@end
